<template>
  <div id="app">
    <h2>{{ message }}</h2>
    <el-upload
      ref="upload"
      class="upload-demo"
      action
      :limit="1"
      :on-exceed="handleExceed"
      :auto-upload="false"
      :on-change="handleFileChange"
      :show-file-list="false"
    >
      <template #trigger>
        <el-button type="primary" style="margin-right: 10px;">上传excel</el-button>
      </template>
      <el-button type="success" @click="download">下载pdf</el-button>
      <el-button type="success" @click="downloadVNode">下载pdf虚拟节点</el-button>
    </el-upload>

    <hr style="margin-bottom: 20px;" />
    <div class="output-box">
      <div id="output"></div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import * as XLSX from "xlsx/xlsx.mjs";
import { downloadPDF } from "./tool.js"
import { ElLoading,genFileId } from 'element-plus'
import html2pdf from "html2pdf.js";

const message = ref("excel转pdf合成测试版");

//公共样式设置
// const commonStyle = '<style>tr:first-child td{ background-color: #BDD7EE;} td { border: 1px solid #000; padding: 8px; }</style>'
const commonStyle = '<style>td { border: 1px solid #000; padding: 8px; }</style>'
//添加基础信息，如公司logo，公司名称
const companyLogo = ref('https://static.wxb.com.cn/frontEnd/images/login-manager/header-logo.png')
const companyName = ref('心有灵犀科技股份有限公司')
const baseInfo = ref(`<img src="${companyLogo.value}" alt="logo" style="width: 115px;height: 32px;">
    <div style="display: flex;justify-content: center;"><div style="margin: 10px 0;font-weight: 700;font-size: 25px;">${companyName.value}</div></div>`)

//sheet名称数据集合    
const sheet_name_list = ref([]);
// const catalogueList = computed(() => {
//   let str = ''
//   sheet_name_list.value.forEach((item, index) => {
//     str += `<div style="display: flex;justify-content: left;"><a href="#md${index}" style="margin: 10px 0;font-size: 20px;custor: pointer;">${item}</a></div>`
//   })
//   return str 
// })

let allHtml = '';
let loadingInstance = null;
//处理excel文件
const handleFile = (file) => {
  const outputElement = document.getElementById("output");
  outputElement.innerHTML = baseInfo.value;
  allHtml = baseInfo.value;

  loadingInstance = ElLoading.service({
    text: '解析中...',
  });

  const f = file;
  const reader = new FileReader();
  reader.onload = function (e) {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    sheet_name_list.value = workbook.SheetNames;
    console.log("sheet_name_list", sheet_name_list);

    let loadLoadingNum = sheet_name_list.value.length;
    if (loadLoadingNum === 0) {
      loadingInstance.close();
      loadingInstance = null
    }

    for (let i = 0; i < sheet_name_list.value.length; i++) {
      setTimeout(() => {
        const html_str = XLSX.utils.sheet_to_html(
          workbook.Sheets[sheet_name_list.value[i]]
        );

        // const newDiv = document.createElement("div")
        const sheet_tit = `<div id='md${i}' style="display: flex;justify-content: left;"><div style="margin: 10px 0;font-size: 20px;">${sheet_name_list.value[i]}</div></div>` 
        const styledHtml = sheet_tit + html_str
          // .replace(
          //   "<table>",
          //   '<table style="border-collapse: collapse; width: 100%;margin: 20px 0">'
          // )
          .replace("<body>", `<body>${commonStyle}`)
          .replace(/\><\/td>/g, 'style="border: none" ></td>');
        // newDiv.innerHTML = styledHtml
        // outputElement.appendChild(newDiv)
        allHtml += styledHtml
        console.log("allHtml", allHtml);
        console.log('sheet_name_list.length',sheet_name_list.length)
        console.log('i',i)

        loadLoadingNum--;
        if (loadLoadingNum === 0) {
          loadingInstance.close()
          loadingInstance = null
        }
      },i*1500)
    }
  };
  reader.readAsArrayBuffer(f);
};

const pdfName = ref("test");
const download = () => {
  downloadPDF(document.querySelector("#output"), pdfName.value);
}
const downloadVNode = () => {
  const element = document.createElement("div");
  element.innerHTML = allHtml;

  html2pdf().from(element).save();
};

const upload = ref()
const handleExceed = (files) => {
  console.log('files',files)
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}
const handleFileChange = (e) => {
  handleFile(e.raw)
}
</script>

<style lang="less">
// .output-box {
//   border: 1px solid #ccc;
//   height: 60vh;
//   overflow-y: scroll;
// }
</style>